package com.cloudcc.mobile.view.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEventR;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.model.Jxmedel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.NearByUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.BeauFilterChildAdapter;
import com.cloudcc.mobile.adapter.BeauFilterChildAdapter.OnSelectItemListener;
import com.cloudcc.mobile.adapter.BeauFilterParentAdapter;
import com.cloudcc.mobile.adapter.BeauFilterParentAdapter.OnItemSelectListener;
import com.cloudcc.mobile.adapter.BeauListAdapterType;
import com.cloudcc.mobile.adapter.BeauListAdapterType.OnClickItem;
import com.cloudcc.mobile.adapter.BeauListAdapterType.onItemMenuClickListener;
import com.cloudcc.mobile.adapter.BeauShiTuAdapter;
import com.cloudcc.mobile.bull.GongniuAddShopActivity;
import com.cloudcc.mobile.dao.CallLogDao;
import com.cloudcc.mobile.dao.impl.CallLogDaoImpl;
import com.cloudcc.mobile.dialog.CreatePopwindow;
import com.cloudcc.mobile.entity.JurisdictionEntity;
import com.cloudcc.mobile.entity.beau.BeauListEntity;
import com.cloudcc.mobile.entity.beau.BeauListFilterEntity;
import com.cloudcc.mobile.entity.beau.BeauListFilterEntity.SearchFilter;
import com.cloudcc.mobile.entity.beau.BeauListFilterEntity.SearchFilter.FilterChild;
import com.cloudcc.mobile.entity.beau.BeauListFilterEntity.SearchView;
import com.cloudcc.mobile.entity.beau.BeauRecordTypeEntity;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.event.BeauEventList.BeauListEvent;
import com.cloudcc.mobile.event.BeauEventList.BeauListFilterEvent;
import com.cloudcc.mobile.event.refresh.RefreshEntiityListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.presenter.BeauPresenter;
import com.cloudcc.mobile.presenter.BeauPresenter.FilterCondition;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.util.CenterDialog;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.SystemUtils;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.BeauListActivity;
import com.cloudcc.mobile.view.activity.BeauSortActivity;
import com.cloudcc.mobile.bull.BullNewJobActivity;
import com.cloudcc.mobile.view.activity.RecordtypeActivity;
import com.cloudcc.mobile.view.main.fragment.BaseListFragment;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.viewgroup.SoftKeyboardHandledLinearLayout;
import com.cloudcc.mobile.weight.viewgroup.SoftKeyboardHandledLinearLayout.SoftKeyboardVisibilityChangeListener;
import com.cloudcc.mobile.widget.listview.CloudCCListView;
import com.cloudcc.mobile.widget.listview.CloudCCListView.OnRefreshOrLoadMoreListener;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.utils.AnimViewUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.zbar.lib.CaptureActivity;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.cloudcc.mobile.R.id.beau_bottom_sort;

public class BeauListFragmentType extends BaseListFragment implements onItemMenuClickListener, OnClickItem,
        SoftKeyboardVisibilityChangeListener, OnRefreshOrLoadMoreListener, CenterDialog.OnCenterItemClickListener, CreatePopwindow.CreatPop {
    @Bind(R.id.toastHintContent)
    TextView toastHintContent;
    @Bind(R.id.topLayoutBackg)
    RelativeLayout topLayoutBackg;
    @Bind(R.id.imgDeletes)
    ImageView imgDeletes;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;

    private String mEns = RunTimeManager.getInstance().getlanguage();
    private boolean mIs = true;
    @Bind(R.id.testsss)
    CloudCCListView mListView;

    @Bind(R.id.layoutHeight)
    LinearLayout layoutHeight;

    @Bind(R.id.container1)
    RelativeLayout rlButtom;


    @Bind(R.id.topLineLayout)
    LinearLayout topLineLayout;

    @Bind(R.id.et_search_content)
    EditText mSearchContent;

    @Bind(R.id.ll_searchparent)
    LinearLayout ll_searchparent;

    @Bind(R.id.no_result_layout_beaulist)
    LinearLayout noResultLayout;

    @Bind(R.id.container)
    SoftKeyboardHandledLinearLayout container;
    @Bind(R.id.tv_hight)
    TextView tv_hight;
    @Bind(R.id.btnLayoutSearch)
    RelativeLayout btnLayoutSearch;
    @Bind(R.id.right_lingdang)
    ImageView right_lingdang;
    public static String mToastStr;
    //上面视图的图片
//	@Bind(R.id.menu_image_bg)
//	ImageView menu_image_bg;
    @Bind(R.id.menu_add_icon)
    ImageView menu_add_icon;
    @Bind(R.id.textViewCoustom)
    TextView textViewCoustom;

    @Bind(R.id.toutextview)
    TextView toutextview;
    @Bind(R.id.sx_iv)
    ImageView sx_iv;
    @Bind(R.id.paixu_iv)
    ImageView paixu_iv;
    @Bind(R.id.create_iv)
    ImageView create_iv;
    private PopupWindow mCreatepop;
    private PopupWindow mSearchView;
    @Bind(R.id.popdingwei)
    TextView popdingwei;
    private BeauPresenter mBeauPresenter = new BeauPresenter();

    private BeauListAdapterType mAdapter;
    private String drlxrurl;
    private int[] mFilterSelectArray;
    /**
     * 是否是第一次请求 如果是第一次请求 就 先请求 筛选条件
     */
    private boolean isFristRequest = true;
    /**
     * 过滤器数据
     */
    private CallLogDao callLogDao;//请求服务器的封装方法类
    private BeauListFilterEntity mFilter;
    List<String> lisyd;
    private boolean isShowShiTuView;
    private boolean isShowShiTuViewx;
    private Cursor phone, cursor;
    private FilterCondition mFilterCondition = null;
    private Context context;
    private String paixifangshi;
    private int jilusize;
    public List<BeauRecordTypeEntity.DataBean> DataBean_x;
    protected String username, usernumber;
    private CenterDialog centerDialog;

    //访问联系人数据
    private ContentResolver contentResolver;
    private String uri_raw = "content://com.android.contacts/raw_contacts";
    private String uri_phone = "content://com.android.contacts/data/phones";
    private boolean lxrqx;
    private boolean cjlxrqx;
    private BeauEventList.JurisdictionEvent event;

    private CreatePopwindow popwindow;//新建弹窗
    private String folderId;//选中的文件id

    private List<SearchView> listSerch;//报表专用

    //消息数量
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
    @Bind(R.id.message_num_99)
    TextView message_num_99;

    @Override
    public void init() {
        Log.d("onClickEdit", "进入列表页面");
        EventEngine.register(this);
//        int ooo = lisyd.size();
        initHeader();
        android.util.Log.i("TAG", "bingding" + RunTimeManager.getInstance()
                .getServerBinding());
        mFilterCondition = new FilterCondition();
        mListView.getLoadMore().setOnScrollListener(mScrollListener);
        mListView.setOnRefreshOrLoadMoreListener(this);
        //初始化dialog
        centerDialog = new CenterDialog(mContext, R.layout.dialog_layout, new int[]{R.id.dialog_cancel, R.id.dialog_sure});
        popwindow = new CreatePopwindow(mContext);
        popwindow.setOnCreatPopListener(this);
        centerDialog.setOnCenterItemClickListener(this);


        if (CallName != null && CallName.length() != 0) {
            mSearchContent.setText(CallName);
        } else {
            if ("en".equals(mEns)) {
                mSearchContent.setHint("Search  " + mEntityName.toLowerCase());
            } else {
                mSearchContent.setHint("搜索  " + mEntityName);
            }
        }
        mListView.requestRefresh();
        if ("en".equals(mEns)) {
            textViewCoustom.setText("Recent " + mEntityName);
        } else {
            textViewCoustom.setText("最近" + mEntityName);
        }

        if (mEntityId.equals("report")) {
            rlButtom.setVisibility(View.GONE);
        }
        container.setOnSoftKeyboardVisibilityChangeListener(this);

        initReceiver();

        initEdit();
        setHttp();
        //铃铛点击事件

        listSerch = new ArrayList<>();

        right_lingdang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EventEngine.post(new MenuToggleEventR(true, true));
            }
        });
        showShiTuView();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        mToastStr = "mA";
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        // TODO Auto-generated method stub
        create_iv.setBackgroundResource(R.drawable.create);
        paixu_iv.setBackgroundResource(R.drawable.ico_beau_sort);
        String Unames = RunTimeManager.getInstance().getUserName();
        mCreatepop = null;
        if ("xunjian".equals(RunTimeManager.getInstance().getgongniu())) {
            topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
            toastHintContent.setText(getString(R.string.save_success));
            layoutTop.setVisibility(View.VISIBLE);
            topLayoutBackg.setVisibility(View.GONE);
            new AnimViewUtils().appearToast(topLayoutBackg);
            RunTimeManager.getInstance().setGongniu("xxx");
        } else if ("jilu".equals(RunTimeManager.getInstance().getgongniu())) {
            topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
            toastHintContent.setText(getString(R.string.save_success));
            layoutTop.setVisibility(View.VISIBLE);
            topLayoutBackg.setVisibility(View.GONE);
            new AnimViewUtils().appearToast(topLayoutBackg);
            RunTimeManager.getInstance().setGongniu("xxx");
        } else if ("gnmd".equals(RunTimeManager.getInstance().getgongniu())) {
            topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
            toastHintContent.setText(getString(R.string.save_success));
            layoutTop.setVisibility(View.VISIBLE);
            topLayoutBackg.setVisibility(View.GONE);
            new AnimViewUtils().appearToast(topLayoutBackg);
            RunTimeManager.getInstance().setGongniu("xxx");
        }
        if (RunTimeManager.getInstance().getIsBaocun()) {
            mSearchContent.setText("");
            requestData();
            if (!Unames.isEmpty()) {
                topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
                if (mNewUrl.contains("obj=003")) {
                    toastHintContent.setText(getString(R.string.lianxirens) + "\"" + Unames + "\"" + getString(R.string.yibaocun));
                }
                if (mNewUrl.contains("obj=004")) {
                    toastHintContent.setText(getString(R.string.qianzaikehus) + "\"" + Unames + "\"" + getString(R.string.yibaocun));
                } else {
                    return;
                }
                layoutTop.setVisibility(View.VISIBLE);
                topLayoutBackg.setVisibility(View.GONE);
                new AnimViewUtils().appearToast(topLayoutBackg);
                RunTimeManager.getInstance().setIsbaocun(false);
            } else {
                topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
                toastHintContent.setText(getString(R.string.save_success));
                layoutTop.setVisibility(View.VISIBLE);
                topLayoutBackg.setVisibility(View.GONE);
                new AnimViewUtils().appearToast(topLayoutBackg);
                RunTimeManager.getInstance().setIsbaocun(false);
            }
        }
        if (!"mA".equals(mToastStr)) {
            setToast();
        }
        MessageSetNCL();
    }

    public static void setToastStr(String mToast) {
        mToastStr = mToast;
    }

    public void setToast() {
        toastHintContent.setText(mToastStr);
        layoutTop.setVisibility(View.VISIBLE);
        topLayoutBackg.setVisibility(View.GONE);
        new AnimViewUtils().appearToast(topLayoutBackg);
    }


    private void initEdit() {
        mSearchContent
                .setOnEditorActionListener(new EditText.OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            InputMethodManager imm = (InputMethodManager) v
                                    .getContext().getSystemService(
                                            Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                            clickSearch();
                            return true;
                        }
                        return false;
                    }

                });

    }

    private void initHeader() {


        Bundle bundle = getArguments();
        if (bundle != null) {
            mEntityName = bundle.getString(ExtraConstant.EXTRA_NAME, "对象列表");
            mEntityId = bundle.getString(ExtraConstant.EXTRA_ID, "");
            mNewUrl = bundle.getString(ExtraConstant.EXTRA_URL, "");
            ImageID = bundle.getString("imageId", "");
            callLog = bundle.getString("callLog", "");
            CallName = bundle.getString("CallName", "");
            Log.d("---mEntityName", mEntityName);
        }
        ((TextView) findViewById(R.id.header_title)).setText(mEntityName);
        try {
            Class drawable = R.drawable.class;
            Log.d("ceshirenwu", ImageID + "::");
            Field field = drawable.getField(ImageID + "_1");
            int id = field.getInt(field.getName());
            menu_add_icon.setImageBitmap(null);
            menu_add_icon.setBackgroundResource(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isUp = true;
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 1;// 标记上次滑动位置
    private OnScrollListener mScrollListener = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case OnScrollListener.SCROLL_STATE_IDLE:// 屏幕停止滚动的时候
                    scrollFlag = false;
                    showToolbar();
                    break;
                case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                    if (mAdapter != null) {
                        mAdapter.resetMenu();
                    }
                    scrollFlag = true;
                    break;
                case OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                    scrollFlag = false;
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (scrollFlag) {
                if (firstVisibleItem > lastVisibleItemPosition
                        || currentPage == 1) {// 上滑
                    isUp = false;
                    hideToolbar();
                } else if (firstVisibleItem < lastVisibleItemPosition) {// 下滑
                    isUp = true;
                    showToolbar();
//                    rlButtom.setVisibility(View.VISIBLE);
                } else {
                    return;
                }
                lastVisibleItemPosition = firstVisibleItem;
                android.util.Log.i("TAG", "lastVisibleItemPosition" + lastVisibleItemPosition);
            } else {
                showToolbar();
            }
        }
    };

    public void clickSearch() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mSearchContent.getWindowToken(), 0);
        mListView.requestRefresh();
    }

    private String mEntityName = "对象列表";
    private String mEntityId;
    private String mNewUrl;
    private String ImageID;
    private String callLog;
    private String CallName;

    /**
     * 刷新服务器的菜单列表
     */
    private void requestFilter() {
        mBeauPresenter.getBeanFilter(mEntityId);
    }

    @OnClick(R.id.btnLayoutSearch)
    public void clickMore() {
        BeauListActivity parentActivity = (BeauListActivity) getActivity();
        parentActivity.close();
        if (mIs) {
            showShiTuView();
            Drawable nav_up = getResources().getDrawable(R.drawable.listviewdown);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            mListView.setVisibility(View.GONE);
//        	topLineLayout.setVisibility(View.VISIBLE);
            mIs = false;
        } else {
            Drawable nav_up = getResources().getDrawable(R.drawable.listviewup);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            PopuWindowUtils.dissmiss(mSearchView);
            mListView.setVisibility(View.VISIBLE);
//        	topLineLayout.setVisibility(View.GONE);
            mIs = true;
        }

    }

    @OnClick(R.id.back)
    public void clickback() {
        getActivity().finish();
        Log.d("comeback", getActivity().toString());
    }

    /**
     * 显示 视图标签
     */
    private int mShiTuSelectPos = -1;

    private void showShiTuView() {
        if (isShowShiTuView) {
            return;
        }
        if (!hasShiTuViewData()) {
//			showNoFilterToast();
            requestFilter();
            return;
        }
        // 存在数据
        PopuWindowUtils.dissmiss(mSearchView);
        View contentView = (View) View.inflate(mContext,
                R.layout.beau_search_shitu, null);
        ListView listView = (ListView) contentView.findViewById(R.id.listview2);
        BeauShiTuAdapter adapter = new BeauShiTuAdapter(mContext);
        listView.setAdapter(adapter);
        if (mEntityId.equals("report")) {
            SearchView searchView = new SearchView();
            searchView.label = getString(R.string.zuijinbaobiao);
            listSerch.add(searchView);
            listSerch.addAll(mFilter.search_view);
            adapter.changeData(listSerch);
        } else {
            adapter.changeData(mFilter.search_view);
        }
        adapter.setSelectItem(mShiTuSelectPos);

        adapter.setmOnSelectItemListener(new BeauShiTuAdapter.OnSelectItemListener() {
            @Override
            public void onSelectItem(int pos, SearchView t) {
                mShiTuSelectPos = pos;
                folderId = t.id;
//				requestData();
                isUp = true;
                mListView.requestRefresh();
                textViewCoustom.setText(t.label);
                mIs = true;
                mListView.setVisibility(View.VISIBLE);
                PopuWindowUtils.dissmiss(mSearchView);
                Drawable nav_up = getResources().getDrawable(R.drawable.listviewup);
                nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            }
        });
        // 测量listview
        int totalHeightofListView = ViewUtils
                .getTotalHeightofListView(listView);
        DisplayMetrics dm = new DisplayMetrics();
        // 获取屏幕信息
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
        mSearchView = new PopupWindow(contentView, screenWidth,
                LinearLayout.LayoutParams.MATCH_PARENT);
        mSearchView = new PopupWindow(contentView, screenWidth,
                screenHeigh - layoutHeight.getHeight() - getStatusBarHeight());
        mSearchView.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        mSearchView.setFocusable(false);
        mSearchView.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                isShowShiTuView = false;
            }
        });
        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            btnLayoutSearch.getLocationInWindow(a);
            mSearchView.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + btnLayoutSearch.getHeight());
        } else {
            mSearchView.showAsDropDown(btnLayoutSearch);
        }


    }

    private void showShiTuViewx() {
        if (isShowShiTuView) {
            return;
        }
        if (!hasShiTuViewData()) {
//			showNoFilterToast();
            requestFilter();
            return;
        }
        showPopWindow();
    }


    public void showPopWindow() {

    }

    int firstenter = 1;

    @Override
    public void requestData() {
        Log.d("shifouyunxing", "走到了");
        // 取消 视图 popuwindow
        PopuWindowUtils.dissmiss(mSearchView);
        // 获取 检索条件
        if (mFilter == null) {
            return;
        }
        mFilterCondition.pageNum = currentPage;
        if (mFilter.search_filter != null) {
            for (int i = 0; i < mFilter.search_filter.size(); i++) {
                SearchFilter searchFilter = mFilter.search_filter.get(i);

                if (mFilterSelectArray[i] != -1) {
                    FilterChild filterChild = searchFilter.values
                            .get(mFilterSelectArray[i]);
                    mFilterCondition.filterFileds.put(searchFilter.name,
                            filterChild.id);
                }
            }
        }
        // 视图

        if (!ListUtils.isEmpty(mFilter.search_view)) {
            if (firstenter != 1) {
                try {
                    SearchView searchView;
                    if (mEntityId.equals("report")) {//如果是报表使用报表专用list
                        searchView = listSerch.get(mShiTuSelectPos);
                    } else {
                        searchView = mFilter.search_view
                                .get(mShiTuSelectPos);
                    }
                    mFilterCondition.viewId = searchView.id;
                    Log.d("SearchView", searchView.name);

                } catch (Exception e) {
                }
            }
            firstenter = 2;

        }
        // 排序
        mFilterCondition.objectId = mEntityId;
//        if(mFilterCondition.sortFiled == null || mFilterCondition.sortFiled.equals("")){
//            mFilterCondition.sortFiled = "lastmodifydate";
//        }
        // 关键字
        mFilterCondition.keyword = mSearchContent.getText().toString();

        mBeauPresenter.getBeanList(mFilterCondition);
        mFilterCondition.filterFileds.clear();

    }

    // 筛选
    @OnClick(R.id.beau_bottom_filter)
    public void clickFilter() {
        sx_iv.setBackgroundResource(R.drawable.sx_true_iv);
        showFilterView();
    }

    @OnClick(R.id.beau_bottom_create)
    public void setCreate() {
        if ("2017E7E0A946CFB0pu1v".equals(mEntityId)) {
            Intent intent = new Intent(getActivity(), BullNewJobActivity.class);
            startActivity(intent);
            return;
        }

        if ("2017DE04D47827EaSIOo".equals(mEntityId)) {
            Intent intent = new Intent(getActivity(), CaptureActivity.class);
            intent.putExtra("tag", "gongniu");
            startActivity(intent);
            return;
        }
        // Log.d("---mEntityId",mEntityId);
        if (mEntityName.equals("门店")) {
            Intent intent = new Intent(getActivity(), GongniuAddShopActivity.class);
            startActivity(intent);
            return;
        }

        if (mNewUrl.contains("obj=003") || mNewUrl.contains("obj=004")) {

            NearByUtil.startPropertyAnim45(create_iv);
        } else {
            create_iv.setBackgroundResource(R.drawable.create_true_iv);
        }
        Intent intent = new Intent(mContext, CloudWebViewActivity.class);
        intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                .addReturnUrl(mNewUrl));
        intent.putExtra("daoruurl", mNewUrl);
        MonitorParam monitorParam = new MonitorParam(new String[]{"m=save"},
                WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                true, WebSyncDefaultProxy.STEP_FINISH);
        intent.putExtra(
                "callback",
                WebSyncDefaultProxy
                        .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                        .addMonitorParam(monitorParam).addHomeMonitor());
//        startActivity(intent);
        if (mNewUrl.contains("obj=003") || mNewUrl.contains("obj=004")) {

            if (mCreatepop != null) {
                mCreatepop.dismiss();
                NearByUtil.startPropertyAnim00(create_iv);
                mCreatepop = null;
            } else {
                getJurisdiction();
                onEventMainThread(event);
            }

        } else {
            startActivity(intent);
        }


    }

    // 排序
    @OnClick(beau_bottom_sort)
    public void clickSort() {
        if (!hasSortViewData()) {
            showNoFilterToast();
            return;
        }
        paixu_iv.setBackgroundResource(R.drawable.paixu_true_iv);
        Intent intent = new Intent(mContext, BeauSortActivity.class);
        intent.putExtra("sort.filter", (Serializable) mFilter.search_sort);
        intent.putExtra("sort.name", mFilterCondition.sortFiled);
        intent.putExtra("sort.asc", mFilterCondition.sorModel);
        intent.putExtra("sort.title", mEntityName);
        intent.putExtra("sort.nameid", mEntityId);
        startActivityForResult(intent, 1001);
    }

    String NameZh = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("webfanhui", "webfanhui");
        if (resultCode == Activity.RESULT_OK && (mNewUrl.contains("obj=003") || mNewUrl.contains("obj=004")) && requestCode == 666) {
            // ContentProvider展示数据类似一个单个数据库表
            // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
            ContentResolver reContentResolverol = getActivity().getContentResolver();
            // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
            Uri contactData = data.getData();
            // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.

            cursor = getActivity().getContentResolver().query(contactData, null, null, null, null);
            if (cursor == null) {
                return;
            }
            cursor.moveToFirst();
            // 获得DATA表中的名字
            username = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).replaceAll(" ", "");
            // 条件为联系人ID
            String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
            phone = reContentResolverol.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                            + contactId, null, null);
            while (phone.moveToNext()) {
                usernumber = phone
                        .getString(phone
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");


            }
            if (usernumber.length() == 11) {
                drlxrurl = UrlManager.getManager()
                        .addReturnUrl(mNewUrl) + "&name=" + username + (mEntityId.equals("003") ? "&shouji=" : "&phone=") + usernumber;
            } else {
                drlxrurl = UrlManager.getManager()
                        .addReturnUrl(mNewUrl) + "&name=" + username + "&dianhua=" + usernumber;
            }
//            drlxrurl = UrlManager.getManager()
//                    .addReturnUrl(mNewUrl)+"&name="+username+"&shouji="+usernumber;
            Intent intent = new Intent(mContext, CloudWebViewActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_URL, drlxrurl);
            intent.putExtra("daoruurl", mNewUrl);
            MonitorParam monitorParam = new MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());

            startActivity(intent);

        }
        if (resultCode == Activity.RESULT_OK && requestCode == 1001) {
            mFilterCondition.sortFiled = data.getStringExtra("sort.name");
            NameZh = data.getStringExtra("sort.namezh");
            mFilterCondition.sorModel = data.getBooleanExtra("sort.asc", true);
            if (null != mFilterSelectArray) {
                for (int i = 0; i < mFilterSelectArray.length; i++) {
                    mFilterSelectArray[i] = -1;
                }
            }
            isUp = true;
            mListView.requestRefresh();
            hideSortOrFilter();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.beau_list_frag_type;
    }

    private void refresh() {
        if (isFristRequest) {// 如果 mfilter空的话 先获取 筛选条件
            requestFilter();
        } else {
            onRefreshData();
        }
    }

    public boolean iscontinue(String id, String name) {
        if (id.equals(name)) {
            return true;
        }
        return false;
    }

    /**
     * 加载到数据
     *
     * @param event
     */
    public void onEventMainThread(BeauListEvent event) {

        noResultLayout.setVisibility(View.GONE);
        if ((event.isError() && isFromRefresh())
                || ListUtils.isEmpty(event.getData()) && isFromRefresh()) {
//            mListView.empty();
        }
        if (event.isError()) {
            if (isFromRefresh()) {
                mListView.refreshComplete();
                mListView.handlerLoadMoreFinish(true, false);
            } else {
                mListView.handlerLoadMoreError(1002, event.getMessage());
            }
            // Toast.makeText(mContext, event.getMessage(), 0).show();
            return;
        }
        for (int i = 0; i < event.getData().size(); i++) {
            list.add(event.getData().get(i).getId());
        }
        if (ListUtils.isEmpty(event.getData())) {//如果得到数据为空
            onRequestFinish(true, 0);//1：是否为空   2：数据个数
            return;
        } else {
            onRequestFinish(false, event.getData().size());
        }
        if (ListUtils.isEmpty(event.getData()) && !isFromRefresh()) {
            return;
        }
        if (mAdapter == null) {

            mAdapter = new BeauListAdapterType(mContext, mEntityId);
            mAdapter.setOnItemMenuClickListener(this);
            mListView.setAdapter(mAdapter);
            mAdapter.setmOnClickItem(this);
        } else if (!isUp) {
//			mAdapter.notifyDataSetInvalidated();
            mAdapter.notifyDataSetChanged();
            isUp = true;
        } else {
            mAdapter = new BeauListAdapterType(mContext, mEntityId);
            mAdapter.setOnItemMenuClickListener(this);
            mListView.setAdapter(mAdapter);
            mAdapter.setmOnClickItem(this);
//			mAdapter.notifyDataSetInvalidated();

//			mAdapter.notifyDataSetChanged();
        }
        if (isFromRefresh()) {
            Log.d("zoudaolenali", "開始匹配+BeauListEvent");
            mAdapter.changeData(event.getData());

        } else {
            Log.d("zoudaolenali", "開始匹配+BeauListEvent");
            mAdapter.addData(event.getData());
        }
        String fangshi = " 排序方式: 创建时间";
        String fangshi_en = ",sorted by last created";
        int countpage = 0;
        countpage = totalCount / 15;
        if (null != NameZh) {
            if ("en".equals(mEns)) {
                fangshi = "  sortord  " + NameZh;
            } else {
                fangshi = "  排序方式  " + NameZh;
            }

        }
        if (countpage >= currentPage && currentPage >= 1) {
            if (15 < totalCount) {
                if ("en".equals(mEns)) {
                    toutextview.setText(currentPage * 15 + "+items" + fangshi_en);
                } else {
                    toutextview.setText(currentPage * 15 + "+条记录" + fangshi);
                }

            } else if (0 != event.getData().size()) {
                if ("en".equals(mEns)) {
                    if (totalCount != 1) {
                        toutextview.setText(event.getData().size() + "items" + fangshi_en);
                    } else {
                        toutextview.setText(event.getData().size() + "item" + fangshi_en);
                    }
                } else {
                    toutextview.setText(event.getData().size() + "条记录" + fangshi);
                }

            } else {
                if ("en".equals(mEns)) {
                    toutextview.setText(0 + "item" + fangshi_en);
                } else {
                    toutextview.setText(0 + "条记录" + fangshi);
                }

            }
        } else {
            if ("en".equals(mEns)) {
                if (totalCount != 1) {
                    toutextview.setText(totalCount + "items" + fangshi_en);
                } else {
                    toutextview.setText(totalCount + "item" + fangshi_en);
                }
            } else {
                toutextview.setText(totalCount + "条记录" + fangshi);
            }
        }

    }

    /**
     * 检测是否取消关注
     *
     * @param evnet
     */
    public void onEventMainThread(RefreshEntiityListEvent evnet) {
        if (!evnet.isOk()) {
            return;
        }
        String[] data = evnet.getData();
        for (BeauListEntity entity : mAdapter.getData()) {
            if (StringUtils.equals(entity.getId(), data[0])) {
                entity.ismefollow = Boolean.valueOf(data[1]);
                break;
            }
        }
        Log.d("zoudaolenali", "開始匹配+RefreshEntiityListEvent");
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 获取 beau筛选成功
     *
     * @param event
     */
    public void onEventMainThread(BeauListFilterEvent event) {
        if (event.isError()) {
            mListView.refreshComplete();
//            mListView.empty();
            // mLoadMoreLayout.loadMoreError(1002, event.getMessage());
            noResultLayout.setVisibility(View.VISIBLE);
            Toast.makeText(mContext, event.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }
        noResultLayout.setVisibility(View.GONE);
        this.mFilter = event.getData();
        Log.d("zoudaolenali", "開始匹配+BeauListFilterEvent");
        refreshFilterData();
        // 判断 是否 先 刷新
        //
        if (isFristRequest) {
            isFristRequest = false;
            onRefreshData();
        }

    }

    /**
     * 刷新筛选期的将要使用的数据
     */
    private void refreshFilterData() {
        if (mFilter == null) {
            return;
        }
        if (!ListUtils.isEmpty(mFilter.search_filter)) {
            mFilterSelectArray = new int[mFilter.search_filter.size()];
            for (int i = 0; i < mFilterSelectArray.length; i++) {
                mFilterSelectArray[i] = -1;
            }
        }
        if (!ListUtils.isEmpty(mFilter.search_view)) {
            for (int i = 0; i < mFilter.search_view.size(); i++) {
                if (TextUtils
                        .equals(mFilter.search_view.get(i).isdefault, "-1")) {
                    mShiTuSelectPos = i;
                }
            }
        }
    }

    private void onRequestFinish(boolean dataIsEmpty, int num) {
        if (isFromRefresh()) {// 第一次加载 并且数据出现空的话 就显示 空
            mListView.refreshComplete();
            mListView.isfirst();
            if (dataIsEmpty) {
                noResultLayout.setVisibility(View.VISIBLE);
            }
            if (num < 15) {
                mListView.handlerLoadMoreFinish(false, false);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            } else {
                mListView.handlerLoadMoreFinish(false, true);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }
        } else {
            mListView.refreshComplete();
            if (num < 15) {
                mListView.handlerLoadMoreFinish(false, false);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            } else {
                mListView.handlerLoadMoreFinish(false, true);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }
        }
    }

    /**
     * 显示工具栏
     */
    private void showToolbar() {
        if (mEntityId.equals("report")) {
            return;
        }
        PopuWindowUtils.dissmiss(mSearchView);
        if (rlButtom.getVisibility() == View.GONE
                && !container.isKeyboardShown()) {// 没有显示
            rlButtom.setVisibility(View.VISIBLE);
//            YoYo.with(Techniques.SlideInUp).duration(500).playOn(rlButtom);
            YoYo.with(Techniques.SlideInUp).duration(400).playOn(rlButtom);
        }
    }

    /**
     * 隐藏工具栏
     */
    private void hideToolbar() {
        if (rlButtom.getVisibility() == View.VISIBLE) {// 当前在显示
            YoYo.with(Techniques.SlideOutDown).duration(300)
                    .withListener(new AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator arg0) {
                        }

                        @Override
                        public void onAnimationRepeat(Animator arg0) {
                        }

                        @Override
                        public void onAnimationEnd(Animator arg0) {
                            rlButtom.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationCancel(Animator arg0) {
                        }
                    }).playOn(rlButtom);

        }
    }

    @Bind(R.id.bean_search_lv_parent)
    ListView mFilterParentListView;
    @Bind(R.id.bean_search_lv_china)
    ListView mFilterChildListView;
    @Bind(R.id.beau_filter_view_container)
    RelativeLayout beau_filter_view_container;
    @Bind(R.id.beau_filter_view_container_sub)
    LinearLayout beau_filter_view_container_sub;

    @OnClick(R.id.beau_filter_view_container)
    public void clickFilterContainer() {
        hideSortOrFilter();
    }

    /**
     * 隐藏
     */
    private void hideSortOrFilter() {
        // 隐藏
        sx_iv.setBackgroundResource(R.drawable.ico_beau_filter);
        beau_filter_view_container.setVisibility(View.GONE);

    }

    /**
     * 显示筛选
     */
    private void showFilterView() {

        if (!hasFilterViewData()) {
            showNoFilterToast();
            return;
        }

        if (beau_filter_view_container.getVisibility() == View.VISIBLE) {
            hideSortOrFilter();
            return;
        }
        BeauFilterParentAdapter parentAdapter = new BeauFilterParentAdapter(
                mContext);
        mFilterParentListView.setAdapter(parentAdapter);
        parentAdapter.changeData(mFilter.search_filter);
        showChildFilter(mFilter.search_filter.get(0), 0, mFilterChildListView);
        parentAdapter.setmOnIteSelectListener(new OnItemSelectListener() {
            @Override
            public void onSelect(SearchFilter t, int pos) {
                showChildFilter(t, pos, mFilterChildListView);
            }
        });
        beau_filter_view_container.setVisibility(View.VISIBLE);
        beau_filter_view_container.findViewById(R.id.cancel)
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < mFilterSelectArray.length; i++) {
                            mFilterSelectArray[i] = -1;
                        }
                        hideSortOrFilter();
                    }
                });

        beau_filter_view_container.findViewById(R.id.accept)
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        hideSortOrFilter();
                        mListView.requestRefresh();
                        // refresh();
                        // initRequestData();
                    }
                });
    }

    private void showChildFilter(SearchFilter t, int pos, ListView listView) {
        BeauFilterChildAdapter childAdapter = new BeauFilterChildAdapter(
                mContext);
        listView.setAdapter(childAdapter);
        childAdapter.setSelectItem(mFilterSelectArray[pos]);
        childAdapter.changeData(t.values);
        final int pp = pos;
        childAdapter.setmOnSelectItemListener(new OnSelectItemListener() {
            @Override
            public void onSelectItem(int pos, FilterChild t) {
                mFilterSelectArray = new int[mFilterSelectArray.length];

                for (int i = 0; i < mFilterSelectArray.length; i++) {
                    mFilterSelectArray[i] = -1;
                }
                mFilterSelectArray[pp] = pos;
                for (int i = 0; i < mFilterSelectArray.length; i++) {
                    Log.d("zikongjian1", "选择了" + pos + " " + pp + "数组："
                            + mFilterSelectArray[i]);

                }
            }
        });
    }


    @Override
    public void onDestroy() {
        EventEngine.uregister(this);
        if (mSyncReceiver != null) {
            mContext.unregisterReceiver(mSyncReceiver);
        }
        super.onDestroy();
    }


    @Override
    public void onClickPhone(int pos, BeauListEntity t) {
        Log.d("daodichubuchulai", "最后一步" + t.getDianhua() + "sdfnsdjfvbsdjkj"
                + mEntityId);
        if ("contact".equals(mEntityId)) {
            SystemUtils.sendCall(mContext, t.getShouji());
        } else if ("account".equals(mEntityId)) {
            SystemUtils.sendCall(mContext, t.getDianhua());
        } else {
            SystemUtils.sendCall(mContext, t.getPhone());
        }

    }

    @Override
    public void onClickChatter(int pos, BeauListEntity t) {
        enterInfo(t, true);
    }


    @Override
    public void onClickEdit(int pos, BeauListEntity t) {
        Log.d("onClickEdit", "这是跳转");
        Intent intent = new Intent(mContext, CloudWebViewActivity.class);
        intent.putExtra(
                ExtraConstant.EXTRA_URL,
                UrlManager.getManager().addReturnUrl(
                        UrlManager.getManager().getEntityDetailEditUrl(
                                t.getId())));
        MonitorParam monitorParam = new MonitorParam(new String[]{"m=save"},
                WebSyncDefaultProxy.STEP_START,
                new String[]{"/WeiXin_index.action"}, true,
                WebSyncDefaultProxy.STEP_OVERRIDEURL);
        intent.putExtra(
                "callback",
                WebSyncDefaultProxy
                        .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                        .addMonitorParam(monitorParam).addHomeMonitor());
        startActivity(intent);
    }

    @Override
    public void onClickFollow(final int pos, final BeauListEntity t) {
        new OtherPresenter().followRecord(t.getId(), false,
                new RequestListener() {
                    @Override
                    public void onSuccess(Object arg0) {
                        if ("en".equals(mEns)) {
                            if (t.ismefollow) {
                                Toast.makeText(mContext, "Cancel follow success~~", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "Follow success~~", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (t.ismefollow) {
                                Toast.makeText(mContext, "取消追随成功~~", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "追随成功~~", Toast.LENGTH_SHORT).show();
                            }
                        }

                        if (mAdapter != null) {
                            boolean ismefollow = mAdapter.getItem(pos).ismefollow;
                            mAdapter.getItem(pos).ismefollow = !ismefollow;
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(ErrorInfo arg0) {
                        if ("en".equals(mEns)) {
                            if (t.ismefollow) {
                                Toast.makeText(mContext, "Cancel follow the failure~~", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "Follow the failure~~", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (t.ismefollow) {
                                Toast.makeText(mContext, "取消追随失败~~", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "追随失败~~", Toast.LENGTH_SHORT).show();
                            }
                        }


                    }
                });
    }

    @Override
    public void onClickItem(int pos, BeauListEntity t) {
        enterInfo(t, false);
    }

    /**
     * 进入详情页面
     *
     * @param t
     * @param siEdit
     */
    //创建一个数组用来盛放数据的id集合
    List<String> list = new ArrayList<>();

    private void enterInfo(BeauListEntity t, boolean siEdit) {
        for (int i = 0; i < list.size(); i++) {
            Log.d("fasongshuju", "id是::" + list.get(i) + mEntityName);
        }

        Intent intent = new Intent(mContext, BeauInfoActivity.class);
//        Intent intent = new Intent(mContext, Myinformation.class);
        intent.putExtra("beau.name", mEntityName);
        intent.putExtra("beau.nameid", mEntityId);
        intent.putExtra("beau.imageid", ImageID);
        intent.putExtra("beau.ismefollow", t.ismefollow);
        if (siEdit) {
            intent.putExtra("chatter", "chatter");
        }
        intent.putExtra("beau.id", t.getId());
        intent.putExtra("OBJID", t.getOwnerid());//获取对象的id
        intent.putExtra("OBJNAME", t.getOwneridccname());//获取对象的name
        if (callLog != null && callLog.length() != 0) {
            intent.putExtra("callLog", "addphone");//返回变成Home按钮并且添加电话活动
        }
        Log.d("---jxs", t.getDyjxs() + "---");

        intent.putStringArrayListExtra("befnex", (ArrayList<String>) list);
        // .substring(1, t.getId().length() - 1));
        intent.putExtra("beau.edit", siEdit);
        if(mEntityName.equals("营销资产")){
            intent.putExtra("isAssets", true);
        }
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.zhuanchang, 0);
    }

    /**
     * 是否有过滤菜单的数据
     *
     * @return
     */
    private boolean hasFilter() {
        return mFilter != null;
    }

    /**
     * 是否有 过滤中的 视图菜单数据
     *
     * @return
     */
    private boolean hasShiTuViewData() {
        return hasFilter() && !ListUtils.isEmpty(mFilter.search_view);
    }

    private void showNoFilterToast() {
        if ("en".equals(mEns)) {
            Toast.makeText(mContext, " The current object does not set the filter field, go to the search layout - tab layout settings。", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(mContext, " 当前对象没有设置筛选字段，请到搜索布局-》选项卡布局设置。", Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 是否有筛选视图数据
     *
     * @return
     */
    private boolean hasFilterViewData() {
        return hasFilter() && !ListUtils.isEmpty(mFilter.search_filter);
    }

    /**
     * 是否有排序视图数据
     *
     * @return
     */
    private boolean hasSortViewData() {
        return hasFilter() && !ListUtils.isEmpty(mFilter.search_sort);
    }

    public void clickBack(View v) {
        getActivity().finish();
    }

    @Override
    public void onSoftKeyboardShow() {
        rlButtom.setVisibility(View.GONE);
    }

    @Override
    public void onSoftKeyboardHide() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (getActivity().getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            rlButtom.setVisibility(View.VISIBLE);
        }
        PopuWindowUtils.dissmiss(mSearchView);
    }

    private SyncReceiver mSyncReceiver;

    private void initReceiver() {
        mSyncReceiver = new SyncReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ReceiverConstant.RECEIVE_SYNC_WEB);
        filter.addAction(ReceiverConstant.RECEIVE_REFRESH);
        filter.addAction(ReceiverConstant.RECEIVE_DELETE);
        mContext.registerReceiver(mSyncReceiver, filter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.imgDeletes)
    public void onClick() {
        layoutTop.setVisibility(View.GONE);
    }


    @Override
    public void OnCenterItemClick(CenterDialog dialog, View view) {
        switch (view.getId()) {
            case R.id.dialog_sure:
                Intent intentz = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intentz);
                getActivity().finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void creatOne() {
        selectData();
        if (lxrqx) {
            centerDialog.show();
        } else {

            Intent intent = new Intent(mContext, CloudWebViewActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                    .addReturnUrl(mNewUrl));
            intent.putExtra("daoruurl", mNewUrl);
            MonitorParam monitorParam = new MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());
            if (jilusize < 2) {
                Uri uri = ContactsContract.Contacts.CONTENT_URI;
                Intent intentx = new Intent(Intent.ACTION_PICK, uri);
                startActivityForResult(intentx, 666);
            } else {
                Intent intent1 = new Intent(mContext, RecordtypeActivity.class);
                Bundle jllx = new Bundle();
                jllx.putSerializable("JLLX", (Serializable) DataBean_x);
                jllx.putString("mEntityId", mEntityId);
                jllx.putString("drlxr", "drlxr");
                jllx.putString("MURL", mNewUrl);
                intent1.putExtras(jllx);
                startActivity(intent1);
            }
        }
    }

    @Override
    public void creatTow() {
        if (jilusize < 2) {
            Intent intent = new Intent(mContext, CloudWebViewActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                    .addReturnUrl(mNewUrl));
            intent.putExtra("daoruurl", mNewUrl);
            MonitorParam monitorParam = new MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());

            startActivity(intent);

        } else {
            Intent intent1 = new Intent(mContext, RecordtypeActivity.class);
            Bundle jllx = new Bundle();
            jllx.putSerializable("JLLX", (Serializable) DataBean_x);
            jllx.putString("mEntityId", mEntityId);
            jllx.putString("MURL", mNewUrl);
            intent1.putExtras(jllx);
            startActivity(intent1);
        }
    }

    @Override
    public void ondismiss() {
        NearByUtil.startPropertyAnim00(create_iv);
    }

    private class SyncReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mListView.requestRefresh();
        }
    }

    @Override
    public void onRefresh(PtrFrameLayout frame) {
        list.clear();
        refresh();
    }

    @Override
    public void onLoadMore(LoadMoreContainer frame) {
        currentPage++;
        requestData();
    }

    public int totalCount = 0;

    public void onEventMainThread(Jxmedel event) {
        totalCount = event.getTotalCount();
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 记录类型网络请求
     */
    public void setHttp() {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "getObjRecordTypeList");
        if (mNewUrl.contains("obj=003")) {
            params.addBodyParameter("prefix", "003");
        }
        if (mNewUrl.contains("obj=004")) {
            params.addBodyParameter("prefix", "004");
        }
        Log.d("列表值url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupValue"
                + "&objectId=2016360343BD7B2SQ2PO" + "&pageSize=1"
                + "&keyword=");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        Log.d("列表值接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("列表值接口成功-------------------------", arg0.result);
                        Gson gson = new Gson();
                        BeauRecordTypeEntity mDdata = gson.fromJson(arg0.result.toString(),
                                BeauRecordTypeEntity.class);

                        android.util.Log.i("TAG", "aaaaaaaaa" + mDdata);
                        try {
                            jilusize = mDdata.getData().size();
                            DataBean_x = mDdata.getData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                });

    }

    private void createpop() {


        WindowManager wm = getActivity().getWindowManager();

        int hight = wm.getDefaultDisplay().getHeight() - rlButtom.getHeight();

        popwindow.showPopupWindow(mListView, rlButtom.getWidth(), hight);

    }


    //查询联系人数据并放到集合里
    private List<Map<String, String>> selectData() {
        /**
         * 1.先查询raw 获取_id查出所有联系人
         * 2.循环查询-->根据_id去data表中（_id=raw_contacts_id）查询 data1数据
         */
        contentResolver = getActivity().getContentResolver();
        Cursor cursor = contentResolver.query(Uri.parse(uri_raw), new String[]{"_id", "display_name"}, null, null, null);
        //cursor返回的cursor数量不定
        List<Map<String, String>> list = new ArrayList<>();
        if (cursor != null && cursor.moveToNext()) {
            String _id = cursor.getString(0);
            String displayName = cursor.getString(1);
            Map<String, String> map = new HashMap<>();
            map.put("_id", _id);
            map.put("display_Name", displayName);
            //根据_id 去data查手机号
            Cursor cursor1 = contentResolver.query(Uri.parse(uri_phone), new String[]{"data1"}, "raw_contact_id=?", new String[]{_id}, null);
//            Cursor cursor3=contentResolver.query()
            //循环拿到手机号
            StringBuffer sb = new StringBuffer();
            //这里循环拿到手机号是因为有时联系人中 你可能一个人有几个电话
            while (cursor1 != null && cursor1.moveToNext()) {
                sb.append(cursor1.getString(0) + "\n");
            }
            map.put("data1", sb.toString());
            list.add(map);
        } else {
            lxrqx = true;
        }
        return list;
    }


    private void getJurisdiction() {
        callLogDao = new CallLogDaoImpl();
        event = new BeauEventList.JurisdictionEvent();
        if (mNewUrl.contains("obj=003")) {
            callLogDao.getJurisdiction("003", event);
        }
        if (mNewUrl.contains("obj=004")) {
            callLogDao.getJurisdiction("004", event);
        }
    }


    public void onEventMainThread(BeauEventList.JurisdictionEvent event) {
        if (event.isError()) {
            return;
        }
        JurisdictionEntity jurisdictionEntity = event.getData();
        if (jurisdictionEntity.query == true) {
            if (jurisdictionEntity.add == true) {
                createpop();
            } else {
                topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                if (mNewUrl.contains("obj=003")) {
                    toastHintContent.setText(getString(R.string.call_log_dialog_record_call_no));
                }
                if (mNewUrl.contains("obj=004")) {
                    toastHintContent.setText(getString(R.string.creat_qianzai_custom_no));
                }
                layoutTop.setVisibility(View.VISIBLE);
                topLayoutBackg.setVisibility(View.GONE);
                new AnimViewUtils().appearToast(topLayoutBackg);
                NearByUtil.startPropertyAnim00(create_iv);

            }
        }

    }

    public void onEventMainThread(MessageNumX event) {

        message_num_tz.setText(event.messageNumX + "");
        if (event.messageNumX > 0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if (event.messageNumX > 99) {
                message_num_tz.setVisibility(View.INVISIBLE);
                message_num_99.setVisibility(View.VISIBLE);
            }

        } else {
            message_num_tz.setVisibility(View.INVISIBLE);
            message_num_99.setVisibility(View.INVISIBLE);
        }

    }

    private void MessageSetNCL() {
        long messagenum = 0;
        messagenum = RunTimeManager.getInstance().getMessageNx();
        message_num_tz.setText(messagenum + "");

        if (messagenum > 0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if (messagenum > 99) {
                message_num_tz.setVisibility(View.INVISIBLE);
                message_num_99.setVisibility(View.VISIBLE);
            }

        } else {
            message_num_tz.setVisibility(View.INVISIBLE);
            message_num_99.setVisibility(View.INVISIBLE);
        }

    }
}
